﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BF.IBLL.BaseSystem;
using Base.Core.UnityFactory;
using System.Web.UI.HtmlControls;
using System.Web.Security;
using BF.Model;
//using BF.IBLL.HealthResources;
using BF.Membership.BLL;
using BF.Membership.MembershipEF;
using System.Linq.Expressions;
using BF.IBLL.Dictionary;

namespace BF.Web.pages.BaseSystem.UserManagement
{
    public partial class TreeUserList : BasePage
    {
        #region 实例
        Isys_UserInfoBLL iBLL = IOCFactory.GetIOCResolve<Isys_UserInfoBLL>();
        //Ires_HumanResourcesBLL iHumanBLL = IOCFactory.GetIOCResolve<Ires_HumanResourcesBLL>();
        //Idic_DepartmentBLL iBLLDepart = IOCFactory.GetIOCResolve<Idic_DepartmentBLL>();
        /// <summary>
        /// 人员注册视图(排序)
        /// </summary>
        Iview_sys_UserInfo_BLL iBllSysUserInfo = IOCFactory.GetIOCResolve<Iview_sys_UserInfo_BLL>();
        AspnetRolesBLL rolesBLL = new AspnetRolesBLL();
        #endregion


        public string ISWSJ
        {
            get
            {
                if (GetSessionCurrentUserInfo.dic_Organization.gHigherKey == default(Guid))
                { return "TRUE"; }
                return "FALSE";
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //isCanAddUser = GetSysParam("IsCanAddUser");
                if (GetSessionCurrentUserInfo.dic_Organization != null)
                {
                    rootHospitalKey.Value = GetSessionCurrentUserInfo.dic_Organization.gKey.ToString();
                }
                else
                {
                    rootHospitalKey.Value = default(Guid).ToString();
                }
                gTreeHospitalKey.Value = rootHospitalKey.Value;
                BindControl();
                BindList();
            }
        }

        private void BindControl()
        {
            string[] roles = Roles.IsUserInRole(User.Identity.Name, "系统管理员") ? Roles.GetAllRoles() : Roles.GetRolesForUser();
            List<aspnet_Roles> listRoles = rolesBLL.GetList(roles);
            List<ListItem> listItems = new List<ListItem>();
            foreach (var item in listRoles)
            {
                ListItem li = new ListItem(item.RoleName, item.RoleId.ToString());
                listItems.Add(li);
            }
            muljs.DataSource = listItems.ToArray();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        { BindList(); }

        private void BindList()
        {
            List<Guid> userIdList = new List<Guid>();
            ListItem[] listItems = muljs.SelectedItems;
            foreach (var item in listItems)
            {
                foreach (var itemid in iBLL.GetUserIdByRoles(new Guid(item.Value)))
                { userIdList.Add(itemid); }
            }
            int count = 0;
            List<sys_UserInfo> userList = new List<sys_UserInfo>();
            List<View_SysUserInfo> viewUserList = new List<View_SysUserInfo>();
            Guid gChoiceHostKey = default(Guid);//选择查询的机构key
            if (!String.IsNullOrEmpty(gTreeHospitalKey.Value))
            { gChoiceHostKey = Guid.Parse(gTreeHospitalKey.Value); }
            else
            { gChoiceHostKey = GetSessionCurrentUserInfo.dic_Organization.gKey; }
            bool bState = false;
            if (ddlState.SelectedValue == "1")
            { bState = true; }

            System.Linq.Expressions.Expression<Func<View_SysUserInfo, bool>> linqWhere = P => false;

            linqWhere = (P => (userIdList.Count == 0 ? true : userIdList.Contains(P.gUserID)) &&
                (String.IsNullOrEmpty(sLoginName.Text.Trim()) ? true : P.sLoginName.Contains(sLoginName.Text.Trim())) &&
                (String.IsNullOrEmpty(sUserName.Text.Trim()) ? true : P.sUserName.Contains(sUserName.Text.Trim())) &&
                ((gChoiceHostKey == default(Guid)) ? true : P.gOrganizationKey == gChoiceHostKey) &&
                ((ddlState.SelectedValue == "2") ? true : P.iState == bState)
                );

            count = iBllSysUserInfo.GetRowCount(linqWhere);

            viewUserList = iBllSysUserInfo.GetList(linqWhere,
                P => new { P.sOrganizationCode, P.sLoginName },
                new Infrastructure.PageModel(AspNetPager1.CurrentPageIndex),
                true);

            AspNetPager1.RecordCount = count;
            Repeater1.DataSource = viewUserList
                 .Select(Q => new
                 {
                     gUserID = Q.gUserID,
                     sAreaName = GetAreaNameByAreaCode(string.IsNullOrEmpty(Q.sAreaCode) ? "" : Q.sAreaCode),
                     sLoginName = Q.sLoginName,
                     sUserName = Q.sUserName,
                     iState = Q.iState,
                     iStateText = Q.iState == true ? "已启用" : "已停用",
                     sOrganizationName = string.IsNullOrEmpty(Q.sOrganizationName) ? "" : Q.sOrganizationName,
                 }).ToList();
            Repeater1.DataBind();
        }

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            bool result = false;
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox)Repeater1.Items[i].FindControl("chksuserid");
                HtmlInputHidden hd = (HtmlInputHidden)Repeater1.Items[i].FindControl("sLoginName");
                if (cb != null && cb.Checked)
                {
                    Guid gUserID = new Guid(cb.Value);
                    if (User.Identity.Name == hd.Value)
                    { Messages("不能删除当前用户!", this.UpdatePanel1); }
                    else if (hd.Value.ToLower() == "admin")
                    { Messages("系统超级管理员不能被删除!", this.UpdatePanel1); }
                    else
                    { result = iBLL.Delete(P => P.gUserID == new Guid(cb.Value), hd.Value, gUserID); }
                }
            }
            Messages(result ? "删除成功!" : "删除失败!", this.UpdatePanel1);
            BindList();
        }

        protected void lbtnStop_Click(object sender, EventArgs e)
        {
            bool result = false;
            bool iState = hideStop.Value == "1" ? true : false;
            string message = hideStop.Value == "1" ? "启用" : "停用";
            for (int i = 0; i < Repeater1.Items.Count; i++)
            {
                HtmlInputCheckBox cb = (HtmlInputCheckBox)Repeater1.Items[i].FindControl("chksuserid");
                if (cb != null && cb.Checked)
                { result = iBLL.ChangeState(new Guid(cb.Value), iState); }
            }
            Messages(result ? message + "成功!" : message + "失败!", this.UpdatePanel1);
            BindList();
        }

        protected void lbtnQuery_Click(object sender, EventArgs e)
        {
            AspNetPager1.CurrentPageIndex = 1;
        }
    }
}